package com.kamfu.bio.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

/**
 * @program: kamfu
 * @ClassName BioServer5
 * @description:实现任意文件上传
 * @author: liandy
 * @create: 2021-12-30 14:14
 * @Version 1.0
 **/
public class BioFileServer {
    public static void main(String[] args) {
        try {
            ThreadPool threadPool = new ThreadPool();
            //1.建立ServerSocker监听端口
            ServerSocket serverSocket = new ServerSocket(9000);
            System.out.println("服务端启动成功");
            //2.等待客户端连接
            while (true){
                Socket socket = serverSocket.accept();
                System.out.println("新的客户端连接成功");
                //将socket移交给线程池处理
                threadPool.execute(new FileSocketThread(socket));
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class FileSocketThread implements Runnable {
    private Socket socket;

    public FileSocketThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //获取字节输入流
            InputStream inputStream = socket.getInputStream();
            //将字节输入流包装成Data输入流
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            //读取文件后缀名
            String suffix = dataInputStream.readUTF();
            System.out.println("文件后缀名：" + suffix);
            //定义文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream(
                    new File("F:\\kamfu\\src\\main\\resource\\" +
                            UUID.randomUUID().toString() + suffix));
            //字节缓冲数组
            byte[] buf = new byte[1024];
            int len;
            while ((len = dataInputStream.read(buf)) > 0) {
                fileOutputStream.write(buf, 0, len);
            }
            fileOutputStream.flush();
            fileOutputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}